<template>
    <view class="p-l-r">
        <template v-if="dataRows.length > 0">
            <view class="item" v-for="(card, i) in dataRows" :key="card.id">
                <view class="wrap">
                    <view class="cardNo">卡号：{{ card.cardNo }}</view>
                    <view class="m-t-10">余额：￥{{ (Number(card.amount) + Number(card.rewardAmount)).toFixed(2) }}</view>
                    <view class="m-t-10">绑定时间：{{ parseTime(card.activeTime) }}</view>
                </view>
                <view class="action">
                    <nut-button @tap="unbind(card.id, i)">解绑</nut-button>
                    <navigator class="m-l-20" :url="`./recharge/index?id=${card.id}&cardNo=${card.cardNo}`"><nut-button type="primary">充值</nut-button></navigator>
                </view>
            </view>
        </template>
        <view v-else class="empty">未绑定充电卡</view>

        <view class="m-t-30">
            <nut-button type="primary" block size="large" @tap="bind">绑定卡</nut-button>
        </view>
    </view>
</template>

<script lang="ts" setup>
    import { cardsApi, bindApi, unbindApi } from '@/api/ChargingCard';
    import { parseTime } from '@/utils';
    import { showLoading, hideLoading, showModal, showToast, useDidShow } from '@/utils/framework';
    import { ref } from 'vue';

    const dataRows = ref<any[]>([])
    async function queryCards() {
        showLoading()
        const res = await cardsApi()
        hideLoading()
        if(res.data && res.data.length > 0) {
            dataRows.value = res.data
        }
    }


    function bind() {
        showModal({
            title : '输入卡号',
            editable : true,
            async success(res) {
                if(res.confirm) {
                    if(!res.content) return
                    showLoading()
                    const r = await bindApi(res.content)
                    hideLoading()
                    if(r.success) {
                        queryCards()
                        showToast('绑定成功')
                    }else {
                        showToast(r.msg)
                    }
                }
                
            }
        })
    }

    function unbind(id:number, i:number) {
        showModal({
            title : '确定解绑吗',
            async success(res) {
                if(res.confirm) {
                    showLoading()
                    const r = await unbindApi(id)
                    hideLoading()
                    if(r.success) {
                        dataRows.value.splice(i, 1)
                        showToast('解绑成功')
                    }else {
                        showToast(r.msg)
                    }
                }
                
            }
        })
    }

    
    

    useDidShow(() => {
        queryCards()
    })
</script>

<style lang="scss" src="./index.scss"></style>